package config_center

import (
	"context"
	"fmt"
	"payme3000/framework/errorx"
	"strconv"
	"sync"
)

// AtomicInt32 int32类型的配置值
type AtomicInt32 struct {
	sync.RWMutex
	value    int32
	strValue string
}

func NewAtomicInt32(val int32) *AtomicInt32 {
	return &AtomicInt32{
		value:    val,
		strValue: fmt.Sprintf("%d", val),
	}
}

func (a *AtomicInt32) Store(newStrValue string) bool {
	a.Lock()
	defer a.Unlock()

	if a.strValue == newStrValue {
		return false
	}

	newValue, err := strconv.ParseInt(newStrValue, 10, 64)
	if err != nil {
		errorx.Catch(context.Background(), err)
		return false
	}

	a.strValue = newStrValue
	a.value = int32(newValue)

	return true
}

func (a *AtomicInt32) String() string {
	a.RLock()
	defer a.RUnlock()

	return a.strValue
}

func (a *AtomicInt32) Int32() int32 {
	a.RLock()
	defer a.RUnlock()

	return a.value
}
